<?php

namespace addons\ttlock;

use think\Addons;
use think\Config;

class ttlock
{
    private $host = "https://cnapi.ttlock.com/";
    private $client_id = "9ffbee2f97d24f4583d4210c78a406bb";
    private $client_secret = "c034c00dce722e0cd6c96cf714d6f7d0";
    private $username = "17538146984";
    private $password = "qq131452020";
    private $md5Password = "";

    public function __construct()
    {
        $this->client_id = Config::get('site.lock_client_id');
        $this->client_secret = Config::get('site.lock_client_secret');
        $this->username = Config::get('site.lock_username');
        $this->password = Config::get('site.lock_password ');
        $this->md5Password = strtolower(md5($this->password));
    }

    // token
    private function getToken()
    {
        $token = cache('ttlock_' . $this->client_id . '_token');
        $tokenTime = cache('ttlock_' . $this->client_id . '_token_time');
        if (time() > $tokenTime || !$token) {
            $data = $this->Post('oauth2/token', [
                'clientId' => $this->client_id,
                'clientSecret' => $this->client_secret,
                'username' => $this->username,
                'password' => $this->md5Password,
            ]);
            $data = json_decode($data, true);
            if (isset($data['access_token']) && $data['access_token']) {
                $token = $data['access_token'];
            }
            if (isset($data['expires_in']) && $data['expires_in']) {
                $expires_in = time() + $data['expires_in'];
            }
            if ($expires_in && $token) {
                cache('ttlock_' . $this->client_id . '_token', $token);
                cache('ttlock_' . $this->client_id . '_token_time', $expires_in);
            }
        }
        return $token;
    }

    // 新增锁当前的密码
    public function getPassword($look_id, $keyboardPwdName)
    {
        return $this->getRandPassword($look_id, $keyboardPwdName);
    }

    // 随机密码
    public function getRandPassword($look_id, $keyboardPwdName)
    {

        $data = $this->Post('v3/keyboardPwd/get', [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'lockId' => $look_id,
            'keyboardPwdName' => $keyboardPwdName,
            'keyboardPwdType' => 3,
            'startDate' => time() . "000",
            'endDate' => (time() + 3601) . "000",
            'date' => $this->getMillisecond(),
        ]);
        $data = json_decode($data, true);
        if (isset($data['keyboardPwd'])) {
            return $data['keyboardPwd'];
        }
        return '';
    }


    // 自定义密码
    public function add($look_id)
    {
        $this->deleteLookPasswordList($look_id); // 先删除旧的密码
        $password = rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $postdata = [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'lockId' => $look_id,
            'keyboardPwd' => $password,
            'startDate' => $this->getMillisecond(),
            'endDate' => $this->getMillisecond() + 600000,
            'addType' => 1,
            'date' => $this->getMillisecond(),
        ];
        $data = $this->Post('v3/keyboardPwd/add', $postdata);
        $data = json_decode($data, true);

        if (isset($data['keyboardPwdId'])) {
            return $password;
        }
        return '';
    }


    // 删除锁当前的密码id
    public function deleteLookPasswordList($look_id)
    {
        $keyboardPwdList = $this->getLookKeyboardPwdId($look_id);
        if ($keyboardPwdList) {
            foreach ($keyboardPwdList as $item) {
                $this->Post('v3/keyboardPwd/delete', [
                    'clientId' => $this->client_id,
                    'accessToken' => $this->getToken(),
                    'lockId' => $look_id,
                    'keyboardPwdId' => $item['keyboardPwdId'],
                    'deleteType' => 1,
                    'date' => $this->getMillisecond(),
                ]);
            }
        }
    }

    // 获取锁当前的密码id
    public function getLookKeyboardPwdId($look_id)
    {
        $data = $this->Post('v3/lock/listKeyboardPwd', [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'lockId' => $look_id,
            'pageNo' => 1,
            'pageSize' => 100,
            'date' => $this->getMillisecond(),
        ]);
        $data = json_decode($data, true);
        if (isset($data['list']) && isset($data['list'][0])) {
            return $data['list'];
        }
        return false;
    }

    // 锁详情
    public function detail($look_id)
    {
        $data = $this->Post('v3/lock/detail', [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'lockId' => $look_id,
            'date' => $this->getMillisecond(),
        ]);
        echo $data;
        die;
    }

    // 开锁记录
    public function lockRecord($look_id)
    {
        $data = $this->Post('v3/lockRecord/list', [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'lockId' => $look_id,
            'pageNo' => 1,
            'pageSize' => 100,
            'date' => $this->getMillisecond(),
        ]);
        $data = json_decode($data, true);
        foreach ($data['list'] as $item) {
            echo date('Y-m-d H:i:s', $item['lockDate'] / 1000)."<br/>";
        }
        die;
    }

    // 锁列表
    public function getLookList()
    {
        $data = $this->Post('v3/lock/list', [
            'clientId' => $this->client_id,
            'accessToken' => $this->getToken(),
            'pageNo' => 1,
            'pageSize' => 100,
            'date' => $this->getMillisecond(),
        ]);
        echo $data;
        die;
    }

    // 毫秒
    private function getMillisecond()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }

    private function Post($url, $data)
    {
        $url = $this->host . $url;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);//不抓取头部信息。只返回数据
        curl_setopt($curl, CURLOPT_TIMEOUT, 1000);//超时设置
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);//1表示不返回bool值
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));//重点
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        return $response;
    }
}